<template>
  <div class="page-content" v-loading="loading">
    <div class="text-right" v-if="isViewMode">
      <el-button type="primary" :loading="printLoading" @click="printPage">
        <i class="fa fa-print"></i>
        打印
      </el-button>
      <el-button
        icon="el-icon-download"
        type="primary"
        :loading="printLoading"
        @click="handleExport"
      >
        导出
      </el-button>
    </div>
    <div :id="printId">
      <table class="w-100">
        <tr>
          <td colspan="5" class="text-center">
            <h5>保后检查报告</h5>
          </td>
        </tr>
      </table>
      <table class="table table-bordered table-vertical-middle table-sm">
        <colgroup>
          <col width="15%" />
          <col width="10%" />
          <col width="30%" />
          <col width="15%" />
          <col width="30%" />
        </colgroup>
        <tr>
          <td>检查日期</td>
          <td colspan="2" :class="tdClass">
            <span v-if="isViewMode">{{ $utils.dateFormat(editData.check_date, format) }}</span>
            <el-date-picker
              v-else
              v-model="editData.check_date"
              class="input-td w-100"
              type="date"
              format="yyyy年MM月dd日"
              :clearable="false"
              placeholder="请选择检查日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </td>
          <td>上次检查日期</td>
          <td>
            <span v-if="!checkId">{{ $utils.dateFormat(lastDate, format) }}</span>
            <span v-else>{{ $utils.dateFormat(editData.latest_check_date, format) }}</span>
          </td>
        </tr>
        <tr>
          <td rowspan="3">担保基本情况</td>
          <td>客户名称：</td>
          <td>{{ related.customer_name }}</td>
          <td>批次号</td>
          <td>{{ editData.batch_no || '-' }}</td>
        </tr>
        <tr>
          <td colspan="4">
            担保额度（万元）：{{ editData.gua_funds || related.reply_funds }}
            <template v-if="isViewMode">
              （
              <checked-box label="首次" :value="+editData.is_first_check === 1"></checked-box>
              ，
              <checked-box label="续作" :value="+editData.is_first_check === 0"></checked-box>
              ）
            </template>
            <template v-else>
              （
              <el-radio v-model="editData.is_first_check" class="my-radio" label="1">首次</el-radio>
              <el-radio v-model="editData.is_first_check" class="my-radio" label="0">续作</el-radio>
              )
            </template>
          </td>
        </tr>
        <tr>
          <td colspan="4">
            担保期限：起
            {{ $utils.dateFormat(editData.load_date || related.load_date, format) }}，止
            {{ $utils.dateFormat(editData.load_end_date || related.load_end_date, format) }}
          </td>
        </tr>
        <tr>
          <td>检查方式</td>
          <td colspan="2">
            <template v-if="isViewMode">
              <checked-box
                v-for="(label, key) of enumCheckMethod"
                class="mx-2"
                :key="key"
                :label="label"
                :value="editData.check_method === key"
              ></checked-box>
            </template>
            <template v-else>
              <el-radio
                v-model="editData.check_method"
                class="my-radio"
                v-for="(label, key) of enumCheckMethod"
                :key="key"
                :label="key"
              >
                {{ label }}
              </el-radio>
            </template>
          </td>
          <td>走访对象及参加人</td>
          <td :class="tdClass">
            <span v-if="isViewMode">{{ editData.visit_obj_person }}</span>
            <el-input
              v-else
              placeholder="请输入走访对象及参加人"
              v-model="editData.visit_obj_person"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>检查类型</td>
          <td colspan="4">
            <template v-if="isViewMode">
              <checked-box
                v-for="(label, key) of enumCheckType"
                class="mx-2"
                :key="key"
                :label="label"
                :value="editData.check_type === key"
              ></checked-box>
            </template>
            <template v-else>
              <el-radio
                v-model="editData.check_type"
                class="my-radio"
                v-for="(label, key) of enumCheckType"
                :key="key"
                :label="key"
              >
                {{ label }}
              </el-radio>
            </template>
          </td>
        </tr>
        <tr>
          <td colspan="5" class="pb-5">资料收集：</td>
        </tr>
        <tr>
          <td colspan="5">
            <template v-if="isViewMode">
              本次保后收集：
              <checked-box
                v-for="(label, key) of enumBehColl"
                class="mx-2"
                :key="key"
                :label="label"
                :value="curBehColl.includes(key)"
              ></checked-box>
            </template>
            <template v-else>
              <div class="d-flex">
                本次保后收集：
                <el-checkbox-group v-model="curBehColl">
                  <el-checkbox v-for="(label, key) in enumBehColl" :key="key" :label="key">
                    {{ label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </template>
          </td>
        </tr>
        <tr>
          <td colspan="5" class="pb-5">其他资料：</td>
        </tr>
        <template v-for="(p, index) of tableColumn">
          <tr :key="index">
            <td colspan="5" :class="p.class">
              <div v-if="isViewMode" :class="p.divClass">
                {{ p.label }}
                <template v-if="p.selectKey">
                  <checked-box
                    v-for="(label, key) of enumIsOrNot"
                    class="mx-2"
                    :key="key"
                    :label="label"
                    :value="editData[p.selectKey] === key"
                  ></checked-box>
                </template>
                <template v-if="p.inputKey">
                  <span v-if="isViewMode">{{ editData[p.inputKey] }}</span>
                </template>
              </div>
              <div class="d-flex align-items-center" v-else :class="p.divClass">
                <span>{{ p.label }}</span>
                <template v-if="p.selectKey">
                  <el-radio
                    v-model="editData[p.selectKey]"
                    class="my-radio"
                    v-for="(label, key) of enumIsOrNot"
                    :key="key"
                    :label="key"
                  >
                    {{ label }}
                  </el-radio>
                </template>
                <template v-if="p.inputKey">
                  <el-input
                    :type="p.label ? '' : 'textarea'"
                    :rows="5"
                    class="input-td flex-1"
                    :placeholder="p.placeholder"
                    v-model="editData[p.inputKey]"
                  ></el-input>
                </template>
              </div>
            </td>
          </tr>
        </template>
        <tr class="bd-0">
          <td colspan="3" class="text-center">
            检查人： {{ editData.submit_person_name || user.realName }}
          </td>
          <td colspan="2" :class="tdClass">
            <span class="ml-3">日期：</span>
            <span v-if="isViewMode">
              {{ $utils.dateFormat(editData.corp_sign_date, format) }}
            </span>
            <el-date-picker
              v-else
              v-model="editData.corp_sign_date"
              class="input-td flex-1"
              type="date"
              format="yyyy年MM月dd日"
              :clearable="false"
              placeholder="请选择签字日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </td>
        </tr>
        <tr>
          <td>客户签字</td>
          <td colspan="4">
            <div class="d-flex justify-content-around textarea-view align-items-end">
              <div>签字：</div>
              <div>日期：</div>
            </div>
          </td>
        </tr>
      </table>
    </div>

    <div class="text-center pt-2" v-if="!isViewMode">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        保存
      </el-button>
      <el-button :loading="submitLoading" class="btn-long" @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
import { excelTableExport, printA4, domHasClass } from '@vimi/utils-tool'
import {
  enumCheckMethod,
  enumCheckType,
  enumBehColl,
  enumIsOrNot,
} from '@/credit/views/city/self/after/report/enum'
import { mapGetters } from 'vuex'
export default {
  components: {
    'checked-box': {
      props: {
        value: Boolean,
        label: String,
      },
      render(h) {
        const { value, label } = this
        return value
          ? h('span', [h('span', { style: 'font-size: 16px' }, `☑`), h('span', {}, `${label}`)])
          : h('span', [h('span', { class: 'isChecked' }, `□`), h('span', {}, `${label}`)])
      },
    },
  },
  props: {
    queryId: String,
    viewMode: {
      type: Boolean,
      default: false,
    },
    checkId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      enumIsOrNot,
      enumBehColl,
      enumCheckMethod,
      enumCheckType,
      loading: false,
      printLoading: false,
      format: 'yyyy年MM月dd日',
      related: {},
      relatdName: 'customer_related',
      tableName: 'loan_beh_check_report',
      editData: {},
      reportData: {},
      curBehColl: [],
      submitLoading: false,
      lastDate: '',
    }
  },
  computed: {
    ...mapGetters(['user']),
    editDate() {
      return this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
    },
    isViewMode() {
      return this.viewMode
    },
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
    fileName() {
      return `检查报告-${this.related.customer_name}`
    },
    printId() {
      return `${this.queryId}-check-report-${this.editData.id}`
    },
    tableColumn() {
      return [
        { label: '一、外部政策及环境情况：', class: 'bg-light' },
        { label: '1.经济政策是否发生对借款人的不利影响：', selectKey: 'is_out_policy_eco' },
        { label: '2.产业政策是否发生对借款人的不利影响：', selectKey: 'is_out_policy_ind' },
        { label: '3.市场行情是否发生对借款人的不利影响：', selectKey: 'is_out_policy_mar' },
        { label: '4.气象条件是否发生对借款人的不利影响：', selectKey: 'is_out_policy_wea' },
        { label: '5.病、虫灾害是否发生对借款人的不利影响：', selectKey: 'is_out_policy_ill' },
        { label: '6.疫情疫病是否发生对借款人的不利影响：', selectKey: 'is_out_policy_epi' },
        { label: '7.周边环境污染是否发生对借款人的不利影响：', selectKey: 'is_out_policy_env' },
        { label: '二、保后检查情况：', class: 'bg-light' },
        { label: '1.客户资金用途是否发生挪用：', selectKey: 'is_loan_beh_funds_use' },
        { label: '2.生产经营情况是否符合预期：', selectKey: 'is_loan_beh_bus' },
        { label: '3.财务状况是否发生重大变化：', selectKey: 'is_loan_beh_fin' },
        { label: '4.是否发生重大不可抗力事件：', selectKey: 'is_loan_beh_maj' },
        { label: '5.客户家庭情况是否出现较大变数：', selectKey: 'is_loan_beh_fam_var' },
        { label: '6.客户最新资信情况是否较大变化：', selectKey: 'is_loan_beh_credit_var' },
        { label: '7.抵质押物是否发生重大变化：', selectKey: 'is_loan_beh_mort_var' },
        {
          label: '8.关联人/保证人家庭、经营等情况是否出现较大变化：',
          selectKey: 'is_loan_beh_rel_var',
        },
        { label: '9.客户是否存在非法集资、高利贷等行为：', selectKey: 'is_loan_beh_ille' },
        { label: '10.客户客户是否存在其他增加的负债：', selectKey: 'is_loan_beh_add_lia' },
        { label: '11.到期检查，客户是否能够合理安排资金按时还款：', selectKey: 'is_loan_beh_pay' },
        { label: '12.客户是否有新的发展规划：', selectKey: 'is_loan_beh_new_pla' },
        {
          label: '13.其他可能影响还款能力的内容：',
          inputKey: 'loan_beh_other',
          placeholder: '请输入其他可能影响还款能力的内容：',
          class: this.tdClass,
        },
        { label: '三、保后增值服务情况：', class: 'bg-light' },
        { label: '1.提升客户信用意识：', selectKey: 'is_value_add_cre' },
        { label: '2.引导客户规范财务管理：', selectKey: 'is_value_add_fin' },
        { label: '3.向客户普及理财、融资工具：', selectKey: 'is_value_add_cap' },
        { label: '4.引导客户规范土地流转手续：', selectKey: 'is_value_add_lan' },
        { label: '5.引导客户购买农业保险：', selectKey: 'is_value_add_ins' },
        { label: '6.向客户提供最新农业领域研究成果：', selectKey: 'is_value_add_res' },
        { label: '7.搜集客户需求，提供更好体验服务：', selectKey: 'is_value_add_ser' },
        {
          label: '8.其他： ',
          inputKey: 'value_add_other',
          placeholder: '请输入其他',
          class: this.tdClass,
        },
        {
          label: '增值服务备注:',
          inputKey: 'value_add_des',
          class: this.tdClass,
          placeholder: '请输入备注',
        },
        { label: '四、客户近期经营情况概述', class: 'bg-light' },
        {
          label: '',
          inputKey: 'bus_des',
          placeholder: '请输入客户近期经营情况概述',
          class: this.tdClass,
          divClass: 'textarea-view',
        },
        { label: '五、客户近期财务情况概述', class: 'bg-light' },
        {
          label: '',
          inputKey: 'fin_de',
          placeholder: '请输入客户近期财务情况概述',
          class: this.tdClass,
          divClass: 'textarea-view',
        },
        { label: '六、反担保措施变化情况概述', class: 'bg-light' },
        {
          label: '',
          inputKey: 'gua_des',
          placeholder: '请输入反担保措施变化情况概述',
          class: this.tdClass,
          divClass: 'textarea-view',
        },
        { label: '七、异常情况描述', class: 'bg-light' },
        {
          label: '',
          inputKey: 'exc_des',
          placeholder: '请输入异常情况描述',
          class: this.tdClass,
          divClass: 'textarea-view',
        },
        { label: '八、检查结论及处理措施', class: 'bg-light' },
        {
          label: '',
          inputKey: 'check_des',
          placeholder: '请输入检查结论及处理措施',
          class: this.tdClass,
          divClass: 'textarea-view',
        },
      ]
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
    checkId: {
      handler: function () {
        this.getReport()
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    submit() {
      this.editData.cur_beh_coll = this.curBehColl.join(',')
      this.editData.customer_name = this.related.customer_name
      this.editData.corp_name = this.related.corp_name
      this.editData.load_date = this.related.load_date
      this.editData.load_end_date = this.related.load_end_date
      this.editData.gua_funds = this.related.reply_funds
      this.editData.submit_person_name = this.user.realName
      this.editData.submit_person = this.user.userId
      this.editData.customer_related_id = this.queryId
      if (this.editData.id) {
        this.updateData()
      } else {
        this.editData.latest_check_date = this.lastDate
        this.addData()
      }
    },
    updateData() {
      this.submitLoading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.editData.id, this.editData)
        .then(() => {
          this.$message.success('保存成功')
          this.$emit('success', true)
          this.closeDialog()
          this.getReport()
        })
        .catch(() => {
          this.$message.error('保存失败，请重试！！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    addData() {
      this.submitLoading = true
      this.$api
        .addData(this.$serviceName, this.tableName, this.editData)
        .then(() => {
          this.$message.success('保存成功')
          this.$emit('success', true)
          this.closeDialog()
          this.getReport()
        })
        .catch(() => {
          this.$message.error('保存失败，请重试！！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    getReport() {
      this.editData = {}
      this.curBehColl = []
      if (!this.checkId) {
        this.getLastReport()
        return
      }
      this.$api
        .getData(this.$serviceName, this.tableName, {
          'id.eq': this.checkId,
        })
        .then(res => {
          this.editData = res?.data?.[0] ?? {}
          this.reportData = { ...this.editData }
          this.curBehColl = this.editData?.cur_beh_coll?.split(',').filter(item => item) ?? []
        })
    },
    getLastReport() {
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
          },
          { create_time: 'desc' }
        )
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.lastDate = data.check_date
        })
    },
    getData() {
      this.loading = true
      const params = {
        'customer_related_id.eq': this.queryId,
        fields: ['customer_name', 'reply_funds', 'load_date', 'load_end_date', 'corp_name'],
      }
      this.$api
        .getData(this.$serviceName, this.relatdName, params)
        .then(res => {
          this.related = res?.data?.[0] ?? {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    closeDialog() {
      this.editData = { ...this.reportData }
      this.curBehColl = this.reportData?.cur_beh_coll?.split(',').filter(item => item) ?? []
      this.$emit('close', false)
    },
    printPage() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `/deep/ .isChecked {
  font-size: 20px;
}
.input-td {
  background-color: #ffffee;
}
.textarea-view {
  min-height: 60px;
}
.bd-0 > td {
  border: none;
}
.text-indent {
  text-indent: 3rem;
}
.page-content {
  // min-width: 900px;
  padding: 5px;
  margin: 0 auto;
}
.my-radio /deep/ .el-radio__inner {
  position: relative;
  border-radius: 0px;
  &::after {
    border-radius: 0px;
    box-sizing: content-box;
    content: '';
    border: 1px solid #fff;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(1);
    width: 3px;
    transition: transform 0.15s ease-in 0.05s;
    transform-origin: center;
    background-color: unset;
  }
}

.my-radio /deep/ .is-disabled.is-checked .el-radio__inner {
  position: relative;
  border-radius: 0px;
  background: blue;
  &::after {
    border-radius: 0px;
    box-sizing: content-box;
    content: '';
    border: 1px solid white;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(1);
    width: 3px;
    transition: transform 0.15s ease-in 0.05s;
    transform-origin: center;
    background-color: unset;
  }
}
.my-radio /deep/ .is-disabled + span.el-radio__label {
  color: unset;
}`
      )
    },
    handleExport() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const borderAllNone = {
        left: { style: 'none' },
        top: { style: 'none' },
        right: { style: 'none' },
        bottom: { style: 'none' },
      }

      this.printLoading = true
      excelTableExport(this.printId, this.fileName, {
        styles: {
          border: borderAllThin,
          alignment: {
            vertical: 'center',
            horizontal: 'left',
            wrapText: true,
          },
        },
        cellStyles: {
          A1: {
            font: {
              sz: 24,
              name: '方正小标宋简体',
            },
          },
          E1: {
            border: borderAllNone,
          },
        },
        cols: [{ wch: 20.63 }, { wch: 20.0 }, { wch: 34.5 }, { wch: 20.0 }, { wch: 34.0 }],
        rows: {
          43: { hpx: 48 },
          45: { hpx: 48 },
          47: { hpx: 48 },
          49: { hpx: 48 },
          51: { hpx: 48 },
          53: { hpx: 30 },
        },
        cellHandler({ value, td }) {
          const style = {}
          if (domHasClass(td, 'text-center')) {
            style.alignment = { horizontal: 'center' }
          }
          if (domHasClass(td, 'bg-light')) {
            style.fill = { fgColor: { rgb: 'C4BD97' } }
          }
          return { value, style }
        },
      }).finally(() => {
        this.printLoading = false
      })
    },
  },
}
</script>
<style lang="scss" scoped>
/deep/ .isChecked {
  font-size: 20px;
}
.input-td {
  background-color: #ffffee;
}
.textarea-view {
  min-height: 120px;
}
.bd-0 > td {
  border: none;
}
.text-indent {
  text-indent: 3rem;
}
.page-content {
  // min-width: 900px;
  padding: 5px;
  margin: 0 auto;
}
.my-radio /deep/ .el-radio__inner {
  position: relative;
  border-radius: 0px;
  &::after {
    border-radius: 0px;
    box-sizing: content-box;
    content: '';
    border: 1px solid #fff;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(1);
    width: 3px;
    transition: transform 0.15s ease-in 0.05s;
    transform-origin: center;
    background-color: unset;
  }
}

.my-radio /deep/ .is-disabled.is-checked .el-radio__inner {
  position: relative;
  border-radius: 0px;
  background: blue;
  &::after {
    border-radius: 0px;
    box-sizing: content-box;
    content: '';
    border: 1px solid white;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(1);
    width: 3px;
    transition: transform 0.15s ease-in 0.05s;
    transform-origin: center;
    background-color: unset;
  }
}
.my-radio /deep/ .is-disabled + span.el-radio__label {
  color: unset;
}
</style>
